package JUC;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicStampedReference;

public class ABADemo {
    //设置原子版本引用，的初始值为100，版本号为1
    static AtomicStampedReference<Integer> stampedReference =
            new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {
        new Thread(() -> {
            int stamp = stampedReference.getStamp();//获得版本号
            System.out.println(Thread.currentThread().getName() + "stamp 01=>" + stampedReference.getStamp());
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //进行ABA操作
            stampedReference.compareAndSet(100, 101,
                    stampedReference.getStamp(), stampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "stamp 02=>" + stampedReference.getStamp());

            stampedReference.compareAndSet(101, 100,
                    stampedReference.getStamp(), stampedReference.getStamp() + 1);
            System.out.println(Thread.currentThread().getName() + "stamp 03=>" + stampedReference.getStamp());
        }, "T1").start();

        new Thread(() -> {
            int stamp = stampedReference.getStamp(); // 获得版本号
            System.out.println("T2 stamp 01=>" + stamp); // 暂停3秒钟，保证上面线程先执行
            try {
                TimeUnit.SECONDS.sleep(2);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            boolean result = stampedReference.compareAndSet(100, 2019,
                    stamp, stamp + 1);
            System.out.println("T2 是否修改成功 =>" + result);
            System.out.println("T2 最新stamp =>" + stampedReference.getStamp());
            System.out.println("T2 当前的最新值 =>" + stampedReference.getReference());
        }, "T2").start();
    }
}
